import cv2
import numpy as np


def trans_im(path):
    im = cv2.imread(path).astype(np.float64)/255.
    im = cv2.resize(im, (500, 500), interpolation=cv2.INTER_AREA)
    x = np.zeros([1, 3, 500, 500])
    x[0, 0, :, :] = im[:, :, 0]
    x[0, 1, :, :] = im[:, :, 1]
    x[0, 2, :, :] = im[:, :, 2]
    return x


def trans_gt(path):
    im = cv2.imread(path).astype(float)/255.
    im = cv2.resize(im, (500, 500), interpolation=cv2.INTER_AREA)
    x = np.zeros([1, 1, 500, 500])
    x[0, 0, :, :] = im[:, :, 0]
    return x


def crop_and_flatten(gt, y):
    # 使用阈值判断前景
    _gt = (gt > 0.5)

    h, w = _gt.shape
    up, down, left, right = 0, h, 0, w  # 初始化完整范围

    for i in range(h):
        if np.sum(_gt[i]) > 0:
            up = i
            break

    for i in range(h - 1, -1, -1):
        if np.sum(_gt[i]) > 0:
            down = i + 1
            break

    for i in range(w):
        if np.sum(_gt[:, i]) > 0:
            left = i
            break

    for i in range(w - 1, -1, -1):
        if np.sum(_gt[:, i]) > 0:
            right = i + 1
            break

    # 如果没有前景，返回空数组
    if up >= down or left >= right:
        return np.array([]), np.array([])

    return gt[up:down, left:right].flatten(), y[up:down, left:right].flatten()
